package com.qkl.user.controller;


import com.qkl.user.dto.*;
import com.qkl.user.dto.user.ForgetPasswordDto;
import com.qkl.user.entity.MatrixRelation;
import com.qkl.user.entity.Problem;
import com.qkl.user.entity.User;
import com.qkl.user.exception.OperationException;
import com.qkl.user.mapper.MatrixRelationMapper;
import com.qkl.user.mapper.UserMapper;
import com.qkl.user.service.AuthService;
import com.qkl.user.service.MatrixService;
import com.qkl.user.service.UserService;
import com.qkl.user.utils.CaptchaUtils;
import com.qkl.user.utils.RedisCaptchaUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private AuthService authService;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisCaptchaUtil redisCaptchaUtil;
    /**
     * 登录
     */
    @PostMapping("login")
    public ResponseEntity<ExceptionResponse> login(@RequestBody @Validated LoginRequest loginRequest) {
        JwtResponse jwtResponse = authService.login(loginRequest);
        return ResponseEntity.ok(ExceptionResponse.Success(jwtResponse));
    }

    @Autowired
    private MatrixRelationMapper matrixRelationMapper;

   /**
   * 注册
   */
   @PostMapping("register")
    public ResponseEntity<ExceptionResponse> register(@RequestBody @Validated RegisterRequest registerRequest) {
       authService.register(registerRequest);
       return ResponseEntity.ok(ExceptionResponse.Success());
   }
    /**
     * 问题
     */
   @GetMapping("problem")
    public ResponseEntity<ExceptionResponse> problem() {
        List<Problem> problems = userService.getProblems();
        return ResponseEntity.ok(ExceptionResponse.Success(problems));
   }


    @GetMapping("inviteCode/{code}")
    public ResponseEntity<ExceptionResponse> inviteCode(@PathVariable("code") String inviteCode) {
        UserDto user = userService.getUserDtoInviteCode(inviteCode);
        return ResponseEntity.ok(ExceptionResponse.Success(user));
    }
    /**
     * 获取验证码图片（Redis 存储版）
     */
    @GetMapping("/captcha")
    public ResponseEntity<ExceptionResponse> captcha() {
        try {
            // 1. 生成验证码字符和图片（写入内存字节流）
            StringBuilder code = new StringBuilder();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            CaptchaUtils.generateCaptcha(byteArrayOutputStream, code); // 写入字节流

            // 2. 字节流转 Base64 编码（带图片格式前缀，前端可直接使用）
            byte[] imageBytes = byteArrayOutputStream.toByteArray();
            String base64Image = "data:image/png;base64," + Base64.getEncoder().encodeToString(imageBytes);

            // 3. 生成唯一标识 + 存储到 Redis
            String captchaKey = UUID.randomUUID().toString().replace("-", "");
            redisCaptchaUtil.setCaptcha(captchaKey, code.toString());

            // 4. 封装返回结果（captchaKey + base64图片）
            Map<String, String> result = new HashMap<>();
            result.put("captchaKey", captchaKey);
            result.put("base64Image", base64Image); // 前端直接用这个字段渲染图片

            return ResponseEntity.ok(ExceptionResponse.Success(result));
        } catch (Exception e) {
            //throw new RuntimeException("生成验证码失败", e);
            throw new OperationException(-2,"生成验证码失败"+e.getMessage());
        }

    }

    /**
     * 忘记密码
     */
    @PostMapping("forgetPassword")
    public ResponseEntity<ExceptionResponse> forgetPassword(@RequestBody @Validated ForgetPasswordDto forgetPasswordDto) {
        userService.forgetPassword(forgetPasswordDto);
        return ResponseEntity.ok(ExceptionResponse.Success());
    }
}
